// Pipit 日期时间处理模块
#include "pipit_stdlib.h"
#include <time.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
#include <windows.h>

// Windows下的strptime实现
static char* strptime(const char* buf, const char* fmt, struct tm* tm) {
    // 简化的Windows实现，支持常见格式
    char* p = (char*)buf;
    
    if (strstr(fmt, "%Y-%m-%d")) {
        if (sscanf(buf, "%d-%d-%d", &tm->tm_year, &tm->tm_mon, &tm->tm_mday) == 3) {
            tm->tm_year -= 1900;
            tm->tm_mon -= 1;
            p += 10;
            return p;
        }
    }
    
    if (strstr(fmt, "%Y/%m/%d")) {
        if (sscanf(buf, "%d/%d/%d", &tm->tm_year, &tm->tm_mon, &tm->tm_mday) == 3) {
            tm->tm_year -= 1900;
            tm->tm_mon -= 1;
            p += 10;
            return p;
        }
    }
    
    if (strstr(fmt, "%H:%M:%S")) {
        if (sscanf(buf, "%d:%d:%d", &tm->tm_hour, &tm->tm_min, &tm->tm_sec) == 3) {
            p += 8;
            return p;
        }
    }
    
    return NULL;
}

// Windows下的gettimeofday实现
#ifdef _WIN32
static int gettimeofday(struct timeval* tv, void* tz) {
    FILETIME ft;
    ULONGLONG tmpres;

    if (tv != NULL) {
        GetSystemTimeAsFileTime(&ft);
        tmpres = (((ULONGLONG)ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
        tmpres -= 11644473600000000ULL;
        tmpres /= 10;
        tv->tv_sec = (long)(tmpres / 1000000UL);
        tv->tv_usec = (long)(tmpres % 1000000UL);
    }
    return 0;
}
#endif

#else
#include <sys/time.h>
#endif

// 获取当前时间戳（毫秒）
long long pipit_datetime_now() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

// 获取当前日期时间
pipit_datetime_t* pipit_datetime_current() {
    time_t now = time(NULL);
    struct tm* local = localtime(&now);
    
    pipit_datetime_t* dt = malloc(sizeof(pipit_datetime_t));
    dt->year = local->tm_year + 1900;
    dt->month = local->tm_mon + 1;
    dt->day = local->tm_mday;
    dt->hour = local->tm_hour;
    dt->minute = local->tm_min;
    dt->second = local->tm_sec;
    dt->millisecond = 0;
    dt->timezone_offset = 0;
    
    return dt;
}

// 创建指定日期时间
pipit_datetime_t* pipit_datetime_create(int year, int month, int day, int hour, int minute, int second) {
    pipit_datetime_t* dt = malloc(sizeof(pipit_datetime_t));
    dt->year = year;
    dt->month = month;
    dt->day = day;
    dt->hour = hour;
    dt->minute = minute;
    dt->second = second;
    dt->millisecond = 0;
    dt->timezone_offset = 0;
    return dt;
}

// 格式化日期时间为字符串
char* pipit_datetime_format(pipit_datetime_t* dt, const char* format) {
    if (!dt || !format) return NULL;
    
    char* result = malloc(256);
    struct tm tm_time = {0};
    tm_time.tm_year = dt->year - 1900;
    tm_time.tm_mon = dt->month - 1;
    tm_time.tm_mday = dt->day;
    tm_time.tm_hour = dt->hour;
    tm_time.tm_min = dt->minute;
    tm_time.tm_sec = dt->second;
    
    strftime(result, 256, format, &tm_time);
    return result;
}

// 解析日期时间字符串
pipit_datetime_t* pipit_datetime_parse(const char* datetime_str, const char* format) {
    if (!datetime_str || !format) return NULL;
    
    struct tm tm_time = {0};
    char* ptr = strptime(datetime_str, format, &tm_time);
    if (!ptr) return NULL;
    
    pipit_datetime_t* dt = malloc(sizeof(pipit_datetime_t));
    dt->year = tm_time.tm_year + 1900;
    dt->month = tm_time.tm_mon + 1;
    dt->day = tm_time.tm_mday;
    dt->hour = tm_time.tm_hour;
    dt->minute = tm_time.tm_min;
    dt->second = tm_time.tm_sec;
    dt->millisecond = 0;
    dt->timezone_offset = 0;
    
    return dt;
}

// 计算两个日期时间的差值
pipit_timedelta_t* pipit_datetime_diff(pipit_datetime_t* dt1, pipit_datetime_t* dt2) {
    if (!dt1 || !dt2) return NULL;
    
    struct tm tm1 = {0}, tm2 = {0};
    tm1.tm_year = dt1->year - 1900;
    tm1.tm_mon = dt1->month - 1;
    tm1.tm_mday = dt1->day;
    tm1.tm_hour = dt1->hour;
    tm1.tm_min = dt1->minute;
    tm1.tm_sec = dt1->second;
    
    tm2.tm_year = dt2->year - 1900;
    tm2.tm_mon = dt2->month - 1;
    tm2.tm_mday = dt2->day;
    tm2.tm_hour = dt2->hour;
    tm2.tm_min = dt2->minute;
    tm2.tm_sec = dt2->second;
    
    time_t time1 = mktime(&tm1);
    time_t time2 = mktime(&tm2);
    
    long long diff_seconds = time2 - time1;
    
    pipit_timedelta_t* delta = malloc(sizeof(pipit_timedelta_t));
    delta->days = diff_seconds / (24 * 3600);
    delta->hours = (diff_seconds % (24 * 3600)) / 3600;
    delta->minutes = (diff_seconds % 3600) / 60;
    delta->seconds = diff_seconds % 60;
    delta->milliseconds = 0;
    
    return delta;
}

// 添加时间间隔
pipit_datetime_t* pipit_datetime_add_delta(pipit_datetime_t* dt, pipit_timedelta_t* delta) {
    if (!dt || !delta) return NULL;
    
    struct tm tm_time = {0};
    tm_time.tm_year = dt->year - 1900;
    tm_time.tm_mon = dt->month - 1;
    tm_time.tm_mday = dt->day + delta->days;
    tm_time.tm_hour = dt->hour + delta->hours;
    tm_time.tm_min = dt->minute + delta->minutes;
    tm_time.tm_sec = dt->second + delta->seconds;
    
    mktime(&tm_time);
    
    pipit_datetime_t* new_dt = malloc(sizeof(pipit_datetime_t));
    new_dt->year = tm_time.tm_year + 1900;
    new_dt->month = tm_time.tm_mon + 1;
    new_dt->day = tm_time.tm_mday;
    new_dt->hour = tm_time.tm_hour;
    new_dt->minute = tm_time.tm_min;
    new_dt->second = tm_time.tm_sec;
    new_dt->millisecond = dt->millisecond;
    new_dt->timezone_offset = dt->timezone_offset;
    
    return new_dt;
}

// 获取星期几
int pipit_datetime_weekday(pipit_datetime_t* dt) {
    if (!dt) return -1;
    
    struct tm tm_time = {0};
    tm_time.tm_year = dt->year - 1900;
    tm_time.tm_mon = dt->month - 1;
    tm_time.tm_mday = dt->day;
    tm_time.tm_hour = dt->hour;
    tm_time.tm_min = dt->minute;
    tm_time.tm_sec = dt->second;
    
    mktime(&tm_time);
    return tm_time.tm_wday; // 0=Sunday, 1=Monday, ..., 6=Saturday
}

// 判断是否为闰年
int pipit_datetime_is_leap_year(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// 获取月份的天数
int pipit_datetime_days_in_month(int year, int month) {
    static const int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month < 1 || month > 12) return 0;
    
    if (month == 2 && pipit_datetime_is_leap_year(year)) {
        return 29;
    }
    return days[month - 1];
}

// 获取时间戳（Unix时间戳）
long long pipit_datetime_to_timestamp(pipit_datetime_t* dt) {
    if (!dt) return 0;
    
    struct tm tm_time = {0};
    tm_time.tm_year = dt->year - 1900;
    tm_time.tm_mon = dt->month - 1;
    tm_time.tm_mday = dt->day;
    tm_time.tm_hour = dt->hour;
    tm_time.tm_min = dt->minute;
    tm_time.tm_sec = dt->second;
    
    return (long long)mktime(&tm_time);
}

// 从时间戳创建日期时间
pipit_datetime_t* pipit_datetime_from_timestamp(long long timestamp) {
    time_t t = (time_t)timestamp;
    struct tm* tm_time = localtime(&t);
    
    pipit_datetime_t* dt = malloc(sizeof(pipit_datetime_t));
    dt->year = tm_time->tm_year + 1900;
    dt->month = tm_time->tm_mon + 1;
    dt->day = tm_time->tm_mday;
    dt->hour = tm_time->tm_hour;
    dt->minute = tm_time->tm_min;
    dt->second = tm_time->tm_sec;
    dt->millisecond = 0;
    dt->timezone_offset = 0;
    
    return dt;
}

// 计时器实现
#ifdef _WIN32
#include <windows.h>

// Windows计时器实现
struct pipit_timer_t {
    LARGE_INTEGER start_time;
    LARGE_INTEGER end_time;
    int running;
};

pipit_timer_t* pipit_timer_create() {
    pipit_timer_t* timer = malloc(sizeof(pipit_timer_t));
    timer->running = 0;
    return timer;
}

void pipit_timer_start(pipit_timer_t* timer) {
    if (!timer) return;
    QueryPerformanceCounter(&timer->start_time);
    timer->running = 1;
}

void pipit_timer_stop(pipit_timer_t* timer) {
    if (!timer) return;
    QueryPerformanceCounter(&timer->end_time);
    timer->running = 0;
}

double pipit_timer_elapsed(pipit_timer_t* timer) {
    if (!timer) return 0.0;
    
    LARGE_INTEGER end_time;
    if (timer->running) {
        QueryPerformanceCounter(&end_time);
    } else {
        end_time = timer->end_time;
    }
    
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    
    return (double)(end_time.QuadPart - timer->start_time.QuadPart) / frequency.QuadPart;
}

#else
// Unix/Linux计时器实现
struct pipit_timer_t {
    struct timeval start_time;
    struct timeval end_time;
    int running;
};

pipit_timer_t* pipit_timer_create() {
    pipit_timer_t* timer = malloc(sizeof(pipit_timer_t));
    timer->running = 0;
    return timer;
}

void pipit_timer_start(pipit_timer_t* timer) {
    if (!timer) return;
    gettimeofday(&timer->start_time, NULL);
    timer->running = 1;
}

void pipit_timer_stop(pipit_timer_t* timer) {
    if (!timer) return;
    gettimeofday(&timer->end_time, NULL);
    timer->running = 0;
}

double pipit_timer_elapsed(pipit_timer_t* timer) {
    if (!timer) return 0.0;
    
    struct timeval end_time;
    if (timer->running) {
        gettimeofday(&end_time, NULL);
    } else {
        end_time = timer->end_time;
    }
    
    return (end_time.tv_sec - timer->start_time.tv_sec) + 
           (end_time.tv_usec - timer->start_time.tv_usec) / 1000000.0;
}
#endif